﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;

namespace DevExpress.MailClient.Win.Controls.eMap
{
    public partial class ucRegionsManagement : PRO_DOCS.BLL.WIN.Templates.DevxPermissionUserControlTemplate
    {
        bool IMAGE_CHANGED
        { get; set; }

        private PRO_DOCS.DAL.Database.MapCategory _cURRENT_SELECTED_MAP_CATEGORY;
        private PRO_DOCS.DAL.Database.MapCategory CURRENT_SELECTED_MAP_CATEGORY
        {
            get { return _cURRENT_SELECTED_MAP_CATEGORY; }
            set { _cURRENT_SELECTED_MAP_CATEGORY = value; }
        }


        private PRO_DOCS.DAL.Database.MapCategoryRegion _cURRENT_SELECTED_MAP_CATEGORY_REGION;
        private PRO_DOCS.DAL.Database.MapCategoryRegion CURRENT_SELECTED_MAP_CATEGORY_REGION
        {
            get { return _cURRENT_SELECTED_MAP_CATEGORY_REGION; }
            set { _cURRENT_SELECTED_MAP_CATEGORY_REGION = value; }
        }

        private string GET_MAP_CATEGORY_REGION_IMAGE_PATH(Guid mAP_CATEGORY_REGION_ID, string iMAGE_MAP_PATH)
        {
            string file_path = string.Empty;
            List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHE> mapCategorysavingPathes = CURRENT_SELECTED_MAP_CATEGORY.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHy.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHEs.ToList();
            for (int i = 0; i < mapCategorysavingPathes.Count; i++)
            {

                file_path = (Path.Combine(mapCategorysavingPathes[i].ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATH, iMAGE_MAP_PATH));

                if (new FileInfo(file_path).Exists)
                {
                    break;
                }
                else
                {
                    file_path = string.Empty;
                }
            }
            return file_path;
        }

        public ucRegionsManagement()
        {
            InitializeComponent();

            List<PRO_DOCS.DAL.Database.MapCategory> mapCategories = (from mapCategory in PRO_DOCSDatabaseDataContext.MapCategories
                                                                     where mapCategory.IsDeleted.Value.Equals(false)
                                                                     select mapCategory).ToList();

            gridRegionsCategories.DataSource = mapCategories;
        }

        private void gridView2_FocusedRowChanged(object sender, XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                if (e.FocusedRowHandle > -1)
                {
                    CLEAR_INPUTS_DATA();

                    int map_category_id = (gridView2.GetRow(e.FocusedRowHandle) as PRO_DOCS.DAL.Database.MapCategory).MapCategoryID;

                    CURRENT_SELECTED_MAP_CATEGORY = (from category in PRO_DOCSDatabaseDataContext.MapCategories
                                                     where category.MapCategoryID.Equals(map_category_id)
                                                     select category).FirstOrDefault();

                    txtMapCategoryName.Text = CURRENT_SELECTED_MAP_CATEGORY.MapCategoryName;

                    //1. Load the Map category Regions..

                    RELOAD_MAP_CATEGORY_REGIONS();

                    GET_SELECTED_MAP_REGION();

                }
            }
            catch (Exception ex)
            {
                string abc = ex.Message;
            }
        }

        private void RELOAD_MAP_CATEGORY_REGIONS()
        {
            gcMapCategoryRegions.DataSource = (from mapRegions in PRO_DOCSDatabaseDataContext.MapCategoryRegions
                                               where (
                                               mapRegions.MapCategoryID.Value.Equals(CURRENT_SELECTED_MAP_CATEGORY.MapCategoryID)
                                               && mapRegions.IsDeleted.Value.Equals(false)
                                               )
                                               select mapRegions).ToList();


        }

        public void DELETE_MAP_REGION()
        {
            if (!CURRENT_SELECTED_MAP_CATEGORY_REGION.MapRegionID.Equals(Guid.Empty))
            {
                PRO_DOCSDatabaseDataContext.proc_MapCategoryRegionsDelete
                    (CURRENT_SELECTED_MAP_CATEGORY_REGION.MapRegionID);
                gridView1.DeleteSelectedRows();
            }
        }

        private void gridView1_FocusedRowChanged(object sender, XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            try
            {
                if (e.FocusedRowHandle > -1)
                    GET_SELECTED_MAP_REGION();
            }
            catch (Exception ex)
            {
                string abc = ex.Message;
            }
        }

        private void GET_SELECTED_MAP_REGION()
        {
            Guid map_category_region_id = (gridView1.GetRow(gridView1.FocusedRowHandle) as PRO_DOCS.DAL.Database.MapCategoryRegion).MapRegionID;
            CURRENT_SELECTED_MAP_CATEGORY_REGION = (from region in PRO_DOCSDatabaseDataContext.MapCategoryRegions
                                                    where region.MapRegionID.Equals(map_category_region_id)
                                                    select region).FirstOrDefault();

            txtMapCategoryName.Text = CURRENT_SELECTED_MAP_CATEGORY.MapCategoryName;
            txtRegionName.Text = CURRENT_SELECTED_MAP_CATEGORY_REGION.MapRegionName;
            numRegionLatitude.Value = Convert.ToDecimal(CURRENT_SELECTED_MAP_CATEGORY_REGION.MapRegionLatitide.Value.ToString());
            numRegionLogitude.Value = Convert.ToDecimal(CURRENT_SELECTED_MAP_CATEGORY_REGION.MapRegionLogitude.Value.ToString());
            memoRegionDescription.Text = CURRENT_SELECTED_MAP_CATEGORY_REGION.MapRegionDescription;



            txtRegionImage.Tag = CURRENT_SELECTED_MAP_CATEGORY_REGION.MapRegionImage;
            picRegionImage.Image = null;
            string fileImagePath = GET_MAP_CATEGORY_REGION_IMAGE_PATH(CURRENT_SELECTED_MAP_CATEGORY_REGION.MapRegionID, txtRegionImage.Tag.ToString());

            if (new FileInfo(fileImagePath).Exists)
            {
                picRegionImage.Image = Image.FromFile(fileImagePath);
                //txtRegionImage.Tag = fileImagePath;
                //txtRegionImage.Text = CURRENT_SELECTED_MAP_CATEGORY_REGION.MapRegionImage;
            }
            else
            {
                picRegionImage.Image = null;
            }
        }

        string UPLOADED_IMAGE
        { get; set; }
        private void btnUploadImage_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.ShowHelp = true;
            ofd.Title = "Select the Region Image";
            ofd.Filter = "Image file|" + "*.png; *.jpg; *.jpeg; *.bmp; *.gif";
            if (ofd.ShowDialog().Equals(DialogResult.OK))
            {
                picRegionImage.Image = Image.FromFile(ofd.FileName);
                UPLOADED_IMAGE = ofd.FileName;
                //txtRegionImage.Text = new FileInfo(ofd.FileName).Name;
                IMAGE_CHANGED = true;
            }
        }

        public void SAVE_UPDATE_MAP_REGION()
        {
            dxErrorProvider1.ClearErrors();

            bool savingAccepted = !string.IsNullOrEmpty(txtRegionName.Text) && picRegionImage.Image != null;// && numRegionLatitude.Value > 0 && numRegionLogitude.Value > 0;

            if (savingAccepted)
            {
                if (CURRENT_SELECTED_MAP_CATEGORY_REGION.MapRegionID.Equals(Guid.Empty)) //it is new added
                {
                    Guid new_map_region_id = Guid.NewGuid();

                    UPLOAD_REGION_IMAGE(new_map_region_id);

                    PRO_DOCSDatabaseDataContext.proc_MapCategoryRegionsInsert
                        (
                            new_map_region_id,
                            CURRENT_SELECTED_MAP_CATEGORY.MapCategoryID,
                            txtRegionName.Text,
                            memoRegionDescription.Text,
                            txtRegionImage.Tag.ToString(),
                            Convert.ToDouble(numRegionLogitude.Value.ToString()),
                            Convert.ToDouble(numRegionLatitude.Value.ToString()),
                            false
                        );

                    RELOAD_MAP_CATEGORY_REGIONS();

                    IMAGE_CHANGED = false;
                }
                else
                {
                    if (IMAGE_CHANGED)
                    {
                        UPLOAD_REGION_IMAGE(CURRENT_SELECTED_MAP_CATEGORY_REGION.MapRegionID);
                    }
                    PRO_DOCSDatabaseDataContext.proc_MapCategoryRegionsUpdate
                       (
                           CURRENT_SELECTED_MAP_CATEGORY_REGION.MapRegionID,
                           CURRENT_SELECTED_MAP_CATEGORY.MapCategoryID,
                           txtRegionName.Text,
                           memoRegionDescription.Text,
                           txtRegionImage.Tag.ToString(),
                           Convert.ToDouble(numRegionLogitude.Value.ToString()),
                           Convert.ToDouble(numRegionLatitude.Value.ToString()),
                           false
                       );


                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcRegionName, txtRegionName.Text);
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcRegionLogitude, numRegionLogitude.Value.ToString());
                    gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gcRegionLatitude, numRegionLogitude.Value.ToString());

                    IMAGE_CHANGED = false;
                }
            }
            else
            {
                if (string.IsNullOrEmpty(txtRegionName.Text))
                {
                    dxErrorProvider1.SetError(txtRegionName, PRO_DOCS.BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Region Name"), XtraEditors.DXErrorProvider.ErrorType.Information);
                }

                if (!IMAGE_CHANGED)
                {
                    dxErrorProvider1.SetError(txtRegionImage, PRO_DOCS.BLL.WIN.Properties.ErrorProviderMessages.Default.InputLeftBlank.Replace("{name}", "Region Image"), XtraEditors.DXErrorProvider.ErrorType.Information);
                }

            }
        }




        private bool UPLOAD_REGION_IMAGE(Guid new_map_region_id)
        {
            bool image_uploaded = false;
            List<PRO_DOCS.DAL.Database.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHE> mapCategorysavingPathes = CURRENT_SELECTED_MAP_CATEGORY.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHy.ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATHEs.ToList();
            for (int i = 0; i < mapCategorysavingPathes.Count; i++)
            {
                
                if (new DirectoryInfo(mapCategorysavingPathes[i].ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATH).Exists)
                {
                    FileInfo uploladed_file = new FileInfo(UPLOADED_IMAGE);

                    string new_file_Id = Guid.NewGuid().ToString() + uploladed_file.Extension;

                    string file_path = (Path.Combine(mapCategorysavingPathes[i].ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATH, new_file_Id));

                    uploladed_file.CopyTo(file_path, true);
                    //get the thumb Image

                    string thumb_file_path = (Path.Combine(mapCategorysavingPathes[i].ARCHIVE_DEPARTMENTS_STORAGES_HEIRARCHY_PHYSICAL_PATH, "thumb_" + new_file_Id));

                    new PRO_DOCS.BLL.WIN.Utilities.ImagesManager().ScaleImage(Image.FromFile(file_path), 200, 200).Save(thumb_file_path);

                    txtRegionImage.Tag = new_file_Id;

                    image_uploaded = true;
                    break;
                }
            }
            return image_uploaded;
        }

        public void CLEAR_INPUTS_DATA()
        {
            CURRENT_SELECTED_MAP_CATEGORY_REGION = new PRO_DOCS.DAL.Database.MapCategoryRegion();

            txtRegionName.Text = string.Empty;
            txtRegionImage.Text = string.Empty;
            txtRegionImage.Tag = string.Empty;
            numRegionLatitude.Value = 0;
            numRegionLogitude.Value = 0;
            memoRegionDescription.Text = string.Empty;
            IMAGE_CHANGED = false;
            picRegionImage.Image = null;
        }


        internal void ADD_NEW_MAP_REGION()
        {
            CLEAR_INPUTS_DATA();
        }
    }
}
